<!--多级型号-->
<template>
  <div>
    <div class="model">
        <a-row>
            <a-col :offset="2" v-for="(item,index) in modelData" :key="index">
                <div class="panel">
                    <div class="header flex between">
                        <div class="left flex">
                            <a-space>
                                <label>
                                    型号分类：
                                    <a-select v-model="item.modelClassify.value" :disabled="source == 'order'" class="width200" :options="modelClassifyList" @change="handleModelClassifyChange(item.modelClassify.value,index)"></a-select>
                                </label>
                                <template v-if="source != 'order'">
                                    <a href="javascript:;" style="margin-left:20px;" @click="productClassifyShow=true">新建规格</a>
                                    <a-checkbox style="margin-left:20px;" v-model="item.isAddImg" @change="handleAddImageChecked(item.isAddImg)">添加图片</a-checkbox>
                                </template>
                            </a-space>
                        </div>
                        <div class="right">
                            <a href="javascript:;" @click="handleRemoveModelClassify(index)" v-if="source != 'order' && modelData.length!=1">移除</a>
                        </div>
                    </div>
                    <div class="body flex start">
                        <div class="left width100 text_right">
                            <template v-if="item.data.length>0">型号：</template>
                        </div>
                        <div class="right">
                            <a-row :gutter="10"  v-if="item.data.length>0">
                                <template v-for="(item2,index2) in item.data">
                                    <a-tag closable @close.prevent="handleRemoveModel(index,index2)" :key="index2">{{item2.label}}</a-tag>
                                </template>
                            </a-row>
                            <a-row>
                                <a-space>
                                    <a href="javascript:;" v-if="source != 'order'" @click="handleAddModel(item.modelClassify,index)">添加商品型号</a>
                                    <div class="desc">
                                        商品型号最多添加9种
                                    </div>
                                </a-space>
                            </a-row>
                            <a-row>
                                <div class="desc">
                                    仅支持在一个型号分类下添加更多40张型号图片，建议尺寸：800*800像素
                                </div>
                            </a-row>
                        </div>
                    </div>
                </div>
            </a-col>
        </a-row>
        <a-row v-if="source != 'order' && modelData.length<3">
            <a-col :offset="2">
                <a-button icon="add" @click="handleAddModelClassify">添加型号分类</a-button>
            </a-col>
        </a-row>
        <a-row v-if="modelData.length<3">
            <a-col :offset="2">
                <div class="desc">最多添加三个型号分类</div>
            </a-col>
        </a-row>
    </div>
    <a-form-item label="价格与库存" v-if="tableData.length>0">
        <div class="table_box">
            <a-table bordered :data-source="tableData" :columns="tableColumns" :pagination="false" :rowKey="record=>record.index">
                <template slot="modelPictureTitle"><span class="color_red">*</span></template>
                <template slot="modelPicture" slot-scope="text, record">
                    <ImageUpload v-model="record.modelPicture" :disabled="source == 'order'" class="upload_img"></ImageUpload>
                </template>
                <template slot="marketPriceTitle">市场价格（划线价）</template>
                <template slot="marketPrice" slot-scope="text, record">
                    <a-input-number v-model="record.marketPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="salePriceTitle"><span class="color_red">*</span>销售价格（元）</template>
                <template slot="salePrice" slot-scope="text, record">
                    <a-input-number v-model="record.salePrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="integralPriceTitle"><span class="color_red">*</span>兑换价（积分）</template>
                <template slot="integralPrice" slot-scope="text, record">
                    <a-input-number v-model="record.integralPrice" :disabled="source == 'order'" :precision="0" :min="0" :max="9999999"/>
                </template>
                <template slot="goodsInventoryTitle"><span class="color_red">*</span>库存（件）</template>
                <template slot="goodsInventory" slot-scope="text, record">
                    <a-input-number v-model="record.goodsInventory" :disabled="source == 'order'" :precision="0" :min="0" :max="9999999"/>
                </template>
                <template slot="goodsWeight" slot-scope="text, record">
                    <a-input-number v-model="record.goodsWeight" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="erpCode" slot-scope="text, record">
                    <a-input v-model="record.erpCode" :disabled="source == 'order'" class="input_text"/>
                </template>
                <template slot="rebatePrice" slot-scope="text, record">
                    <a-input-number v-model="record.rebatePrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="membersPrice" slot-scope="text, record">
                    <a-input-number v-model="record.membersPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="internalPrice" slot-scope="text, record">
                    <a-input-number v-model="record.internalPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="oneLevelDistributionPrice" slot-scope="text, record">
                    <a-input-number v-model="record.oneLevelDistributionPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="twoLevelDistributionPrice" slot-scope="text, record">
                    <a-input-number v-model="record.twoLevelDistributionPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="threeLevelDistributionPrice" slot-scope="text, record">
                    <a-input-number v-model="record.threeLevelDistributionPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="supplierPriceTitle"><span class="color_red">*</span>供应商价格（元）</template>
                <template slot="supplierPrice" slot-scope="text, record">
                    <a-input-number v-model="record.supplierPrice" :disabled="source == 'order'" :precision="2" :min="0" :max="9999999"/>
                </template>
                <template slot="operation" slot-scope="text, record, index">
                    <a v-if="source != 'order'" href="javascript:;" class="delete" @click="handleRemovePriceInventory(index)">移除</a>
                </template>
            </a-table>
        </div>
    </a-form-item>
    <ProductSpecs :visible="productClassifyShow" @cancel="handleProductClassifyCancel"></ProductSpecs>
    <ProductModel :visible="productModelShow" :modelClassify="currentModelClassify" @cancel="productModelShow=false;" @submit="handleAddModelSubmit"></ProductModel>
  </div>
</template>

<script>
import ImageUpload from '@/components/antBase/ImageUpload'
import ProductModel from './ProductModel';
import ProductSpecs from './ProductSpecs';
import deepCopy from '@/utils/deepCopy'

const rowColSpanRender=(value,row,index,colIndex)=>{
    //console.log(value,index,row);
    const obj={
        children:value,
        attrs:{},
    };
    let name='column'+colIndex;
    if(row[name] && (row[name].colSpan || row[name].colSpan===0)){
        obj.attrs.colSpan=row[name].colSpan;
    }
    if(row[name] && (row[name].rowSpan || row[name].rowSpan===0)){
        obj.attrs.rowSpan=row[name].rowSpan;
    }
    return obj;
}
const tableColumns=[
    {
        key:'modelPicture',
        dataIndex:'modelPicture',
        slots: { title: 'modelPictureTitle' },
        scopedSlots: { customRender: 'modelPicture' },
    },{
        key:'marketPrice',
        dataIndex:'marketPrice',
        className2:'color_red',
        slots: { title: 'marketPriceTitle' },
        scopedSlots: { customRender: 'marketPrice' },
    },{
        key:'salePrice',
        dataIndex:'salePrice',
        className2:'color_red',
        slots: { title: 'salePriceTitle' },
        scopedSlots: { customRender: 'salePrice' },
    },{
        key:'integralPrice',
        dataIndex:'integralPrice',
        className2:'color_red',
        slots: { title: 'integralPriceTitle' },
        scopedSlots: { customRender: 'integralPrice' },
    },{
        key:'goodsInventory',
        dataIndex:'goodsInventory',
        className2:'color_red',
        slots: { title: 'goodsInventoryTitle' },
        scopedSlots: { customRender: 'goodsInventory' },
    },{
        title:'重量（kg）',
        className:'color_red',
        key:'goodsWeight',
        dataIndex:'goodsWeight',
        scopedSlots: { customRender: 'goodsWeight' },
    },{
        title:'ERP编码',
        className:'color_red',
        key:'erpCode',
        dataIndex:'erpCode',
        scopedSlots: { customRender: 'erpCode' },
    },{
        title:'返利价格（元）',
        key:'rebatePrice',
        dataIndex:'rebatePrice',
        scopedSlots: { customRender: 'rebatePrice' },
    },{
        title:'会员价（元）',
        key:'membersPrice',
        dataIndex:'membersPrice',
        className2:'color_red',
        scopedSlots: { customRender: 'membersPrice' },
    },{
        title:'内部价（元）',
        key:'internalPrice',
        dataIndex:'internalPrice',
        className2:'color_red',
        scopedSlots: { customRender: 'internalPrice' },
    },{
        title:'一级分销佣金（元）',
        key:'oneLevelDistributionPrice',
        dataIndex:'oneLevelDistributionPrice',
        scopedSlots: { customRender: 'oneLevelDistributionPrice' },
    },{
        title:'二级分销佣金（元）',
        key:'twoLevelDistributionPrice',
        dataIndex:'twoLevelDistributionPrice',
        scopedSlots: { customRender: 'twoLevelDistributionPrice' },
    },{
        title:'三级分销佣金（元）',
        key:'threeLevelDistributionPrice',
        dataIndex:'threeLevelDistributionPrice',
        scopedSlots: { customRender: 'threeLevelDistributionPrice' },
    },{
        key:'supplierPrice',
        dataIndex:'supplierPrice',
        className2:'color_red',
        slots: { title: 'supplierPriceTitle' },
        scopedSlots: { customRender: 'supplierPrice' },
    },
    // {
    //     title:'操作',
    //     scopedSlots: { customRender: 'operation' }
    // }
]
const modelData=[
    {
        modelClassify:{
            value:'',
            label:'',
        },
        isAddImg:true,
        isSupplierProduct: false,
        data:[
            // {
            //     label:'',
            //     value:'',
            // }
        ]
    }
]
const tableRowData={
    goodsInventory:'',	//商品库存数量
    erpCode:'',	//erp编码
    goodsWeight:'',	//商品重量（单位：g 克）
    marketPrice:'',	//市场价格（划线价，单位：分）
    integralPrice: '', // 积分价格
    salePrice:'',	//销售价格（单位：分）
    rebatePrice:'',	//返利价格（单位：分）
    membersPrice:'', //会员价
    internalPrice: '', // 内部价
    oneLevelDistributionPrice:'',	//一级分销价格（单位：分）
    twoLevelDistributionPrice:'',	//二级分销价格（单位：分）
    threeLevelDistributionPrice:'',	//三级分销价格（单位：分）
    supplierPrice: '', // 供应商价格（单位：分）
    modelPicture:'',	//商品型号图片
    superiorModelIds:'',
    modelIds:'',
};
const moneyAndIntegralRowData={
    goodsInventory:'',	//商品库存数量
    erpCode:'',	//erp编码
    goodsWeight:'',	//商品重量（单位：g 克）
    marketPrice:'',	//市场价格（划线价，单位：分）
    salePrice:'',	//销售价格（单位：分）
    integralPrice: '', // 积分价格
    supplierPrice: '', // 供应商价格（单位：分）
    modelPicture:'',	//商品型号图片
    superiorModelIds:'',
    modelIds:'',
};
const integralRowData={
    goodsInventory:'',	//商品库存数量
    erpCode:'',	//erp编码
    goodsWeight:'',	//商品重量（单位：g 克）
    marketPrice:'',	//市场价格（划线价，单位：分）
    integralPrice: '', // 积分价格
    supplierPrice: '', // 供应商价格（单位：分）
    modelPicture:'',	//商品型号图片
    superiorModelIds:'',
    modelIds:'',
};
export default {
    components:{
        ImageUpload,
        ProductModel,
        ProductSpecs,
    },
    props:{
        data:{
            type:Array,
            default(){
                return [];
            }
        },
        source: {
            type:String,
            default: ''
        },
        isSupplierProduct: {
            type:Boolean,
            default: false
        },
    },
    data(){
        return {
            tableColumns:deepCopy(tableColumns),
            tableData:[],
            modelData:[],//模型数据
            currentModelClassify:{},

            productModelShow:false,
            modelClassifyList:[],
            productClassifyShow:false,
            purchaseMethod: 0,
        }
    },
    watch:{
        tableData:{
            handler(newArr){
                //this.getModelDataByTableData(newArr);
                this.$emit('change',newArr);
                // this.supplierProductChecked(this.isSupplierProduct);
            },
            deep:true,
            immediate:true,
        },
        isSupplierProduct: {
            handler(val){
                //this.getModelDataByTableData(newArr);
                // this.$emit('change',newArr);
                this.supplierProductChecked(val);
            },
            deep:true,
            immediate:true,
        }
    },
    created(){
        this.getModelClassifyList();
        let tmpData=deepCopy(this.data);
        tmpData.forEach((item,index)=>{
            item.index=index;
        })
        this.getModelDataByTableData(tmpData);
    },
    methods:{
        //关闭分类弹框
        handleProductClassifyCancel(){
            this.productClassifyShow=false;
            this.handleRefreshProductClassify();
        },
        //刷新分类
        handleRefreshProductClassify(){
            this.getClassifyList();
        },
        //获取分类列表
        async getClassifyList(){
            let res=await this.$get('/goods/classify/tree',{
                //shopId:this.userInfo.shopId || ''
            })
            if(res && res.returnCode=='1000'){
                this.commodityClassifyList=res.dataInfo;
            }
        },
        //获取型号分类
        async getModelClassifyList(){
            let res=await this.$get('/goods/modelnorm/list',{
                parentId:0,
                //shopId:this.shopId,   
            })
            if(res && res.returnCode=='1000'){
                res.dataInfo.forEach(item=>{
                    this.modelClassifyList.push({
                        value:item.id,
                        label:item.normName,
                    })
                });                
            }
        },
        //获取型号标题和值
        async getTitleLabelAndValue(id){
            if(!parseInt(id)){
                return {};
            }
            let res = await this.$get('/goods/modelnorm/id',{
                id
            },false,true);
            if(res && res.returnCode=='1000'){
                return {
                    label:(res.dataInfo || {}).normName || '',
                    value:id,
                }
            }
            else {
                return {};
            }
        },
        async getModelClassifyLabelAndValue(modelClassifyId,modelData){
            let obj=await this.getTitleLabelAndValue(modelClassifyId);
            return {
                modelClassify:obj,
                isAddImg:true,
                isSupplierProduct: this.isSupplierProduct,
                data:modelData
            }
        },
        //获取模型数据
        async getModelData(tableData,length=1){
            let tmpData=[];
            for(let i=0;i<length;i++){
                let tmpData2 = tableData.map(item=>{
                    let modelId = item.modelIds.split(',')[i];
                    return this.getTitleLabelAndValue(modelId);
                });
                tmpData.push(Promise.all(tmpData2));
            }
            let modelData = await Promise.all(tmpData);
            console.log('modelData',modelData);
            //return modelData;
            //去重
            let newArr=[];
            let obj={};
            for(let i=0;i<tmpData.length;i++){
                newArr.push([]);
                let item=await tmpData[i];
                //console.log('item',item)
                for(let j=0;j<item.length;j++){
                    //console.log(i,j,obj[item[j].value]);
                    if(!obj[item[j].value]){
                        newArr[i].push(item[j]);
                        obj[item[j].value]=true;                        
                    }
                }
            }
            console.log('new modelData',newArr);
            return newArr;
        }, 
        //数组中是否存在
        isExistDataItem(data,modelClassifyId,modelId){
            //console.log('data',deepCopy(data));
            if(data===undefined || data===null){
                return -1;
            }
            for(let i=0;i<data.length;i++){
                let item=data[i];
                //console.log('item.modelClassifyId,modelClassifyId,item.modelId,modelId',item,item.modelClassifyId,modelClassifyId,item.modelId,modelId)
                if(item.modelClassifyId==modelClassifyId && item.modelId==modelId){
                    return i;
                }
            }
            return -1;
        },
        //获取模型分组数据
        async getModelClassifyData(tableData){
            let modelClassifyIds=(tableData[0].superiorModelIds || '').split(',');
            let modelData=await this.getModelData(tableData,modelClassifyIds.length)
            console.log('modelData',modelData);
            console.log('modelClassifyIds',modelClassifyIds);
            let tmpData=[];
            modelClassifyIds.forEach((modelClassifyId,index)=>{ 
                const obj=this.getModelClassifyLabelAndValue(modelClassifyId,modelData[index]);
                tmpData.push(obj)
            });
            return await Promise.all(tmpData);
        },
        //判断是否整型
        isInt(value){
            return parseFloat(value)==parseFloat(value);
        },
        //第一步 通过data得到modelData
        async getModelDataByTableData(tableData=[]){
            if(tableData.length==0){//没有数据时
                this.modelData=deepCopy(modelData);
            }
            else {//有数据时得到modelData

                this.modelData=await this.getModelClassifyData(tableData);
                //第二步
                this.setTableDataByModelData(tableData,this.modelData);
                //第三步
                this.setTableHeaderByModelData(this.modelData);
            }
        },
        //第二步 设置表格数据
        setTableDataByModelData(tableData,modelData){
            let tmpData=[];
            modelData.forEach(item=>{
                tmpData.push([]);
            })
            console.log('tableData',deepCopy(tableData));
            console.log('modelData',deepCopy(modelData));
            // let modelClassifyIds=[];
            // let modelIds=[];
            // modelData.forEach(item=>{
            //     modelClassifyIds.push(item.modelClassify.value);
            //     item.data(item2=>{
            //         modelIds.push()
            //     });
            // });
            tableData.forEach(item=>{
                let modelClassifyIds=item.superiorModelIds.split(',');
                let modelIds=item.modelIds.split(',');
                console.log('modelClassifyIds,modelIds',modelClassifyIds,modelIds);
                modelClassifyIds.forEach((item2,index2)=>{
                    console.log('tmpData,index2,tmpData[index2],item2,modelIds[index2]',tmpData,index2,tmpData[index2],item2,modelIds[index2])
                    let index=this.isExistDataItem(tmpData[index2],item2,modelIds[index2]);
                    console.log('index',index);
                    if(index==-1){
                        tmpData[index2].push({
                            modelClassifyId:item2,
                            modelId:modelIds[index2],
                            rowSpan:1,
                        });
                    }
                    else {
                        tmpData[index2][index].rowSpan++; 
                    }
                });
            });
            console.log('tmpData',deepCopy(tmpData));
            
            let startRows=0;
            let startRows2=0;
            let startRows3=0;
            if(tmpData[0]){
                tmpData[0].forEach((item,index)=>{
                    //设置行索引
                    for(let i=0;i<item.rowSpan;i++){
                        tableData[startRows+i]['index']=startRows+i;
                        console.log('startRows+i',startRows+i)
                    }
                    //第一列
                    let obj=modelData[0].data[index];
                    tableData[startRows]['column0']={
                        rowSpan:item.rowSpan,
                        label:obj.label,
                        value:obj.value
                    }
                    for(let i=0;i<item.rowSpan-1;i++){
                        tableData[startRows+i+1]['column0']={
                            rowSpan:0,
                            label:obj.label,
                            value:obj.value
                        }
                    }
                    //第二列
                    if(tmpData[1]){
                        let rowSpan2=parseFloat(item.rowSpan / tmpData[1].length);
                        //alert(rowSpan2+'=='+item.rowSpan+'=='+tmpData[1].length);
                        if(this.isInt(rowSpan2)){//是整数
                            tmpData[1].forEach((item2,index2)=>{
                                let obj2=modelData[1].data[index2];
                                tableData[startRows2]['column1']={
                                    rowSpan:rowSpan2,
                                    label:obj2.label,
                                    value:obj2.value
                                }
                                for(let i=0;i<rowSpan2-1;i++){
                                    tableData[startRows2+i+1]['column1']={
                                        rowSpan:0,
                                        label:obj2.label,
                                        value:obj2.value
                                    }
                                }

                                //第三列
                                if(tmpData[2]){
                                    let rowSpan3=parseFloat(rowSpan2 / tmpData[2].length);
                                    if(rowSpan3==1){
                                        tmpData[2].forEach((item3,index3)=>{
                                            let obj3=modelData[2].data[index3];
                                            tableData[startRows3]['column2']={
                                                rowSpan:1,
                                                label:obj3.label,
                                                value:obj3.value
                                            }                                
                                            console.log('startRows,startRows2,startRows3',startRows,startRows2,startRows3);

                                            startRows3++;
                                        });                            
                                    }
                                    else {
                                        console.log('第三列 单独一行被删除，此功能未实现');
                                    }
                                }
                                startRows2+=rowSpan2;
                            });
                        }
                        else {//是小数
                            console.log('第二列 单独一行被删除，此功能未实现');
                        }
                    }
                    startRows+=item.rowSpan;
                });
            }
            this.tableData=tableData;
            console.log('this.tableData',deepCopy(this.tableData));
        },
        //第三步 通过data设置表格头
        setTableHeaderByModelData(modelData=[]){
            let dataObj = {}
            if(this.purchaseMethod == 0 || this.purchaseMethod == 1) {
                dataObj=deepCopy(tableRowData);
            } else if(this.purchaseMethod == 2) {
                dataObj=deepCopy(moneyAndIntegralRowData);
            } else if(this.purchaseMethod == 3) {
                dataObj=deepCopy(integralRowData);
            }
            this.tableColumns = []
            tableColumns.forEach(item => {
                if(dataObj.hasOwnProperty(item.key)){
                    this.tableColumns.push(item)
                }
            })
            // this.tableColumns=deepCopy(tableColumns);
            for(let i=modelData.length-1;i>=0;i--){
                let colIndex=i;
                let item=modelData[i];
                let label="column"+colIndex+"['label']";
                //console.log('item,colIndex',item,colIndex,label)
                this.tableColumns.unshift({
                    title:item.modelClassify.label,
                    key:label,
                    dataIndex:label,
                    customRender:(value,row,index)=>{
                        return rowColSpanRender(value,row,index,colIndex);
                    }
                })
            };  
            console.log('this.tableColumns',this.tableColumns);
            this.supplierProductChecked(this.isSupplierProduct)
            this.integralPriceChecked(this.purchaseMethod)
        },
        //移除型号分类
        handleRemoveModelClassify(index){
            this.modelData.splice(index,1);
            let tableData = this.getTableDataByModelData(this.modelData,this.tableData,false)
            this.setTableDataByModelData(tableData,this.modelData);
            this.setTableHeaderByModelData(this.modelData);
            console.log('this.tableData',this.tableData);
            console.log('this.modelData',this.modelData);
        },
        //添加型号分类
        handleAddModelClassify(){
            for(let i=0;i<this.modelData.length;i++){
                let item=this.modelData[i];
                if(!item.modelClassify.value){
                    this.$message.error('请选择型号分类');
                    return;
                }
                if(item.data.length==0){
                    this.$message.error('请添加商品型号');
                    return;
                }
            }
            this.modelData.push({
                modelClassify:{
                    value:'',
                    label:'',
                },
                isAddImg:true,
                isSupplierProduct: this.isSupplierProduct,
                data:[]
            });
            console.log('this.modelData',this.modelData)
        },
        //型号分类切换
        handleModelClassifyChange(modelClassifyId,index){
            this.modelData[index].data=[];
            //型号分类不能存在相同
            for(let i=0;i<this.modelData.length;i++){
                let item=this.modelData[i];
                if(item.modelClassify.value==modelClassifyId && i!=index){
                    this.modelData[index].modelClassify.value='';
                    this.$message.error('型号分类不能相同')
                    return;
                }
            }
            //设置label值
            this.modelClassifyList.forEach(item=>{
                if(item.value==modelClassifyId){
                    this.modelData[index].modelClassify.label=item.label;
                }
            });
        },
        //添加型号
        handleAddModel(modelClassify,index){
            for(let i=0;i<this.modelData.length;i++){
                let item=this.modelData[i];
                if(!item.modelClassify.value){
                    this.$message.error('请选择型号分类');
                    return;
                }
            }
            if(this.modelData[index].data.length>=9){
                this.$message.error('商品型号最多添加9种')
                return;
            }
            this.currentModelClassify=Object.assign(modelClassify,{
                index
            });
            console.log('this.currentModelClassify',this.currentModelClassify)
            this.productModelShow=true;
        },        
        //添加型号回调
        handleAddModelSubmit(modelData,modelClassify){
            console.log('modelData,modelClassify',modelData,modelClassify)     
            for(let i=0;i<modelData.length;i++){
                let selectModel=modelData[i];
                for(let j=0;j<this.modelData[modelClassify.index].data.length;j++){
                    let model=this.modelData[modelClassify.index].data[j];
                    if(selectModel.value==model.value){
                        this.$message.error('商品型号部分存在相同，请重新选择');
                        return;
                    }
                }
            }
            if(modelClassify.index || modelClassify.index===0){
                this.modelData[modelClassify.index].data.push(...modelData);
            }
            console.log('this.modelData',deepCopy(this.modelData))

            //设置表格数据
            let tableData = this.getTableDataByModelData(this.modelData,this.tableData,true)
            console.log('tableData',deepCopy(tableData));
            this.setTableDataByModelData(tableData,this.modelData);
            this.setTableHeaderByModelData(this.modelData);
            console.log('this.tableData',deepCopy(this.tableData));
            console.error('this.tableColumns',deepCopy(this.tableColumns));
            this.productModelShow=false;
            // this.supplierProductChecked(this.isSupplierProduct)
        },
        //移出型号
        handleRemoveModel(index,index2){
            console.log('index,index2',index,index2);
            this.modelData[index].data.splice(index2,1);
            if(this.modelData[index].data.length==0){
                this.modelData.splice(index,1);
            }
            console.log('this.modelData',this.modelData)

            let tableData = this.getTableDataByModelData(this.modelData,this.tableData,false)
            this.setTableDataByModelData(tableData,this.modelData);
            this.setTableHeaderByModelData(this.modelData);
        },
        //移出价格与库存
        handleRemovePriceInventory(rowIndex){
            console.log('rowIndex',rowIndex)
            console.log('this.tableData',this.tableData);
        },
        
        //通过modelData获取modelClassifyIds
        getModelClassifyIdsByModelData(modelData){
            let modelClassifyIds=[];
            modelData.forEach(item=>{
                console.log(modelData);
                modelClassifyIds.push(item.modelClassify.value);
            });
            return modelClassifyIds;
        },
        isInclude(modelClassifyIds1=[],modelIds1=[],modelClassifyIds2=[],modelIds2=[],isAdd=true){
            console.log(modelClassifyIds1,modelClassifyIds2,modelIds1,modelIds2,isAdd);
            //相等
            if(modelClassifyIds1.join(',')==modelClassifyIds2.join(',') && modelIds1.join(',')==modelIds2.join(',')){
                return true;
            }
            //大于
            if(modelClassifyIds1.length>modelClassifyIds2.length && isAdd===false){
                if(modelClassifyIds1[0]==modelClassifyIds2[0] && modelClassifyIds1[1]==modelClassifyIds2[1] && modelIds1[0]==modelIds2[0] && modelIds1[1]==modelIds2[1] ||
                   modelClassifyIds1[0]==modelClassifyIds2[0] && modelClassifyIds1[2]==modelClassifyIds2[1] && modelIds1[0]==modelIds2[0] && modelIds1[2]==modelIds2[1] ||
                   modelClassifyIds1[1]==modelClassifyIds2[0] && modelClassifyIds1[2]==modelClassifyIds2[0] && modelIds1[1]==modelIds2[0] && modelIds1[2]==modelIds2[1]){
                    return true;
                }
            }
            //小于
            if(modelClassifyIds1.length<modelClassifyIds2.length && isAdd===true){
                if(modelClassifyIds1[0]==modelClassifyIds2[0] && modelClassifyIds1[1]==modelClassifyIds2[1] && modelIds1[0]==modelIds2[0] && modelIds1[1]==modelIds2[1] ||
                   modelClassifyIds1[0]==modelClassifyIds2[0] && modelClassifyIds1[1]==modelClassifyIds2[2] && modelIds1[0]==modelIds2[0] && modelIds1[1]==modelIds2[2] ||
                   modelClassifyIds1[0]==modelClassifyIds2[1] && modelClassifyIds1[1]==modelClassifyIds2[2] && modelIds1[0]==modelIds2[1] && modelIds1[1]==modelIds2[2]){
                    return true;
                }
            }
            return false;
        },
        //通过modelData得到tableData
        getTableDataByModelData(modelData,tableData=[],isAdd=true){
            let tmpTableData=[];
            let modelClassifyIds=this.getModelClassifyIdsByModelData(modelData);
            console.log('modelClassifyIds',deepCopy(modelClassifyIds));
            console.log('modelData',deepCopy(modelData));
            console.log('tableData',deepCopy(tableData));

            if(modelData.length==1){//只有一列
                modelData[0].data.forEach((item,index)=>{
                    let modelIds=[item.value];
                    let addRow=deepCopy(tableRowData);
                    // if(this.purchaseMethod == 0 || this.purchaseMethod == 1) {
                    //     addRow=deepCopy(tableRowData);
                    // } else if(this.purchaseMethod == 2) {
                    //     addRow=deepCopy(moneyAndIntegralRowData);
                    // } else if(this.purchaseMethod == 3) {
                    //     addRow=deepCopy(integralRowData);
                    // }
                    addRow.superiorModelIds=modelClassifyIds.join(',');
                    addRow.modelIds=modelIds.join(',');
                    tmpTableData.push(addRow);
                });
            }
            else if(modelData.length==2){//有两列
                modelData[0].data.forEach((item,index)=>{
                    modelData[1].data.forEach((item2,index2)=>{
                        let modelIds=[item.value,item2.value];
                        let addRow=deepCopy(tableRowData);
                        // if(this.purchaseMethod == 0 || this.purchaseMethod == 1) {
                        //     addRow=deepCopy(tableRowData);
                        // } else if(this.purchaseMethod == 2) {
                        //     addRow=deepCopy(moneyAndIntegralRowData);
                        // } else if(this.purchaseMethod == 3) {
                        //     addRow=deepCopy(integralRowData);
                        // }
                        addRow.superiorModelIds=modelClassifyIds.join(',');
                        addRow.modelIds=modelIds.join(',');
                        tmpTableData.push(addRow);
                    });
                });
            }
            else if(modelData.length==3){//有三列
                modelData[0].data.forEach((item,index)=>{
                    modelData[1].data.forEach((item2,index2)=>{
                        modelData[2].data.forEach((item3,index3)=>{
                            console.log('index,index2,index3',index,index2,index3);
                            let modelIds=[item.value, item2.value, item3.value];
                            let addRow=deepCopy(tableRowData);
                            // if(this.purchaseMethod == 0 || this.purchaseMethod == 1) {
                            //     addRow=deepCopy(tableRowData);
                            // } else if(this.purchaseMethod == 2) {
                            //     addRow=deepCopy(moneyAndIntegralRowData);
                            // } else if(this.purchaseMethod == 3) {
                            //     addRow=deepCopy(integralRowData);
                            // }
                            addRow.superiorModelIds=modelClassifyIds.join(',');
                            addRow.modelIds=modelIds.join(',');
                            tmpTableData.push(addRow);
                        });
                    });
                });
            }
            console.log('tmpTableData',deepCopy(tmpTableData));

            //设置表格数据
            if(tableData.length>0){
                tableData.forEach((item,index)=>{
                    let modelClassifyIds=item.superiorModelIds.split(',');
                    let modelIds=item.modelIds.split(',');
                    tmpTableData.forEach((item2,index2)=>{
                        let tmpModelClassifyIds=item2.superiorModelIds.split(',');
                        let tmpModelIds=item2.modelIds.split(',');

                        if(this.isInclude(modelClassifyIds,modelIds,tmpModelClassifyIds,tmpModelIds,isAdd)){
                            item2.index=index2;
                            item2.goodsInventory=item.goodsInventory;
                            item2.erpCode=item.erpCode;
                            item2.goodsWeight=item.goodsWeight;
                            item2.marketPrice=item.marketPrice;
                            item2.integralPrice=item.integralPrice;
                            item2.salePrice=item.salePrice;
                            item2.rebatePrice=item.rebatePrice;
                            item2.membersPrice=item.membersPrice;
                            item2.internalPrice=item.internalPrice;
                            item2.oneLevelDistributionPrice=item.oneLevelDistributionPrice;
                            item2.twoLevelDistributionPrice=item.twoLevelDistributionPrice;
                            item2.threeLevelDistributionPrice=item.threeLevelDistributionPrice;
                            item2.supplierPrice=item.supplierPrice;
                            item2.modelPicture=item.modelPicture;
                        }
                    });
                });
            }
            return tmpTableData;
        },
        //商品规格信息“添加图片”复选框是否显示
        handleAddImageChecked(data){
            console.log(data)
            for(let i=0;i<this.modelData.length;i++){
                let item=this.modelData[i];
                if(!item.modelClassify.value){
                    this.$message.error('请选择型号分类');
                    return;
                }
                if(item.data.length==0){
                    this.$message.error('请添加商品型号');
                    return;
                }
            }
            this.modelData.forEach(item=>{
                item.isAddImg=data;
            })
            if(data){
                this.tableColumns.splice(this.modelData.length,0,{
                    key:'modelPicture',
                    dataIndex:'modelPicture',
                    slots: { title: 'modelPictureTitle' },
                    scopedSlots: { customRender: 'modelPicture' },
                })
            }
            else {
                this.tableColumns.splice(this.modelData.length,1);
                this.tableData.forEach(item=>{
                    item.modelPicture='';
                })
            }
        },
        // 是否为供应商商品
        supplierProductChecked(val) {
            console.log('supplierProductChecked',val)
            this.modelData.forEach(item=>{
                item.isSupplierProduct=val;
            })
            console.log('hasisSupplierProduct',this.tableColumns.findIndex(item => item.key == 'supplierPrice'))
            if(val){
                if(this.tableColumns.findIndex(item => item.key == 'supplierPrice') > -1) {
                    this.tableColumns.splice(this.tableColumns.findIndex(item => item.key == 'supplierPrice'),1)
                }
                this.tableColumns.push({
                    key:'supplierPrice',
                    dataIndex:'supplierPrice',
                    className2:'color_red',
                    slots: { title: 'supplierPriceTitle' },
                    scopedSlots: { customRender: 'supplierPrice' },
                })
            } else {
                this.tableColumns.splice(this.tableColumns.findIndex(item => item.key == 'supplierPrice'),1)
                console.log(this.tableColumns)
            }
        },
        // 兑换价积分
        integralPriceChecked(purchaseMethod) {
            console.log('integralPrice',purchaseMethod)
            console.log('hasintegralPrice',this.tableColumns.findIndex(item => item.key == 'integralPrice'))
            if(purchaseMethod == 2 || purchaseMethod == 3){
                if(this.tableColumns.findIndex(item => item.key == 'integralPrice') > -1) {
                    this.tableColumns.splice(this.tableColumns.findIndex(item => item.key == 'integralPrice'),1)
                }
                let integralPriceItem = {
                    key:'integralPrice',
                    dataIndex:'integralPrice',
                    className2:'color_red',
                    slots: { title: 'integralPriceTitle' },
                    scopedSlots: { customRender: 'integralPrice' },
                }
                if(purchaseMethod == 2) {
                    this.tableColumns.splice(4, 0, integralPriceItem)
                } else if(purchaseMethod == 3) {
                    this.tableColumns.splice(3, 0, integralPriceItem)
                }
            } else {
                this.tableColumns.splice(this.tableColumns.findIndex(item => item.key == 'integralPrice'),1)
                console.log(this.tableColumns)
            }
        }
    }
}
</script>

<style lang="less" scoped>
.title{
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 24px;
}
.desc{
    color:#ccc;
}
.flex{
    display:flex;
    align-items: center;    
    &.between{
        justify-content: space-between;
    }
    &.start{
        align-items: flex-start;
    }
}
/deep/ .input_text{
    width:200px!important;
    height:32px!important;
    border: 1px solid #d9d9d9!important;
    border-radius: 4px!important;
}
.width100{
    width:100px;
}
.width150{
    width:150px;
}
.width200{
    width:200px;
}
.text_right{
    text-align: right;
}
.color_red{
    color:red;
}
.upload_img{
    /deep/ .ant-upload{
        width: 70px!important;
        height: 70px!important;
        vertical-align: middle;
        display: flex;
        align-items: center;
        justify-content: center;
        img{
            width:70px!important;
            height:70px!important;
            object-fit: cover;
        }
    }
}
.freightType{
    .ant-row{
        margin-bottom: 10px;
        &:last-child{
            margin-bottom: 0;
        }
    }
}
.product_picture{
    width:60px;
    height:60px;
    display: block;
}
.delete{
    white-space: nowrap;
}
.panel{
    border: 1px solid #E6E6E6;
    border-radius: 4px;
    margin-bottom:10px;
	.header{		
        background:#F5F5F5;
        border-bottom:1px solid #E6E6E6;
        padding:3px 15px;
		.left{
            white-space: nowrap;
		}
		.right{
			a{
				white-space: nowrap;
			}
		}
	}
}
.table_box{
    overflow: scroll;
}
</style>

